package com.itheima.aop;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    //采用@Around环绕通知
    @Around("@annotation(com.itheima.anno.Log)")
    public Object logOperation(ProceedingJoinPoint pjp) throws Throwable {
        //方法开始时间
        long startTime = System.currentTimeMillis();

        //执行目标方法
        Object result = pjp.proceed();

        //方法结束时间
        long endTime = System.currentTimeMillis();

        //计算方法运行时间
        long costTime = endTime - startTime;

        //构建日志实体
        OperateLog olog = new OperateLog();
        olog.setOperateEmpId(getCurrentUserId());//操作人ID
        olog.setOperateTime(LocalDateTime.now());//操作时间
        olog.setClassName(pjp.getTarget().getClass().getName());//操作的类名
        olog.setMethodName(pjp.getSignature().getName());//操作的方法名
        olog.setMethodParams(Arrays.toString(pjp.getArgs()));//方法参数
        olog.setReturnValue(result != null ? result.toString() : "void");//返回值
        olog.setCostTime(costTime);//方法执行耗时，单位ms

        //保存日志
        log.info("记录操作日志：{}",olog);
        operateLogMapper.insert(olog);

        return result;
    }

    private Integer getCurrentUserId() {
        return CurrentHolder.getCurrentId();
    }
}